package com.heiyu.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.heiyu.api.request.VirtualDelRequest;
import com.heiyu.api.request.VirtualPutRequest;
import com.heiyu.api.request.VirturalUpdateRequest;
import com.heiyu.api.response.CommonResponse;
import com.heiyu.api.response.VirtualResoponse;
import com.heiyu.api.response.VirturalGetResponse;
import com.heiyu.api.response.model.PicPointInfo;
import com.heiyu.api.response.model.VirtualGetModel;
import com.heiyu.api.response.model.VirtualInfo;
import com.heiyu.api.response.model.VirtualModel;
import com.heiyu.constants.ResponseMsgEnum;
import com.heiyu.controller.ApiBaseController;
import com.heiyu.dao.MarketBaseInfoMapper;
import com.heiyu.dao.UserVirtualAssetsInfoMapper;
import com.heiyu.entity.*;
import com.heiyu.utils.MoneyUtils;
import com.heiyu.utils.RangeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Api(description = "用户虚拟资产")
@RestController
@RequestMapping("api/v1/user/virtual")
public class UserVirtualAssetController extends ApiBaseController {

    @Autowired
    private MarketBaseInfoMapper marketBaseInfoMapper;
    @Autowired
    private UserVirtualAssetsInfoMapper userVirtualAssetsInfoMapper;

    @ApiOperation(value = "获取虚拟资产",notes = "获取虚拟资产信息")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public VirtualResoponse get(){
        VirtualResoponse resoponse = new VirtualResoponse();
        UserInfo userInfo  = getUser();
        if(userInfo == null){
            resoponse.error("用户未登陆");
            return resoponse;
        }
        Map<String,Double> total = this.userVirtualAssetsInfoMapper.persionalTotal(userInfo.getId());
        //获取用户所有资产信息
        UserVirtualAssetsInfo userVirtualAssetsInfo = new UserVirtualAssetsInfo();
        userVirtualAssetsInfo.setUserId(userInfo.getId());
        List<UserVirtualAssetsInfo> list = this.userVirtualAssetsInfoMapper.selectList(userVirtualAssetsInfo);
        List<GlobalShowInfo> showList = this.userVirtualAssetsInfoMapper.persionTotalList(userInfo.getId());
        VirtualModel model = new VirtualModel();
        model.setPointList(Lists.newArrayList());
        model.setCoinList(Lists.newArrayList());
        if(defaultSymbol()){
            model.setTotal(MoneyUtils.formatter(new BigDecimal(total.get("nowTotalPrice")),true));
            model.setDiffPirce(MoneyUtils.formatter(new BigDecimal(total.get("diffPrice")),true));
        }else{
            String str = redisUtils.hget("COIN_GLOBAL","CNY");
            JSONObject obj = JSON.parseObject(str);
            model.setTotal(MoneyUtils.formatter(new BigDecimal(total.get("nowTotalPrice")).multiply(new BigDecimal(obj.getDouble("price_usd"))),true));
            model.setDiffPirce(MoneyUtils.formatter(new BigDecimal(total.get("diffPrice")).multiply(new BigDecimal(obj.getDouble("price_usd"))),true));
        }

        model.setRange(RangeUtil.formatter(new BigDecimal(total.get("percent"))));
        if(CollectionUtils.isNotEmpty(list)){
            VirtualInfo virtualInfo;
            PicPointInfo pointInfo;
            GlobalShowInfo itShowInfo;
            CoinBaseInfo coinBaseInfo;
            BigDecimal totalPrice = new BigDecimal(total.get("nowTotalPrice"));
            Map<String,GlobalShowInfo> showInfoMap = Maps.newHashMap();
            for(int i=0;i<showList.size();i++){
                showInfoMap.put(showList.get(i).getTargetId(),showList.get(i));
            }
            for(int i=0;i<list.size();i++){
                coinBaseInfo = coinBaseInfoUtils.get(list.get(i).getTargetId());
                virtualInfo = new VirtualInfo();
                pointInfo = new PicPointInfo();
                itShowInfo = showInfoMap.get(list.get(i).getTargetId());
                pointInfo.setName(itShowInfo.getSymbol());
                pointInfo.setPrecent(totalPrice.doubleValue()<=0?1000000:itShowInfo.getPriceCny().multiply(list.get(i).getNum()).divide(totalPrice,6,2).multiply(new BigDecimal("1000000")).intValue());
                pointInfo.setPrecentDesc(MoneyUtils.fenToYuan(pointInfo.getPrecent()));
                if(coinBaseInfo != null){
                    virtualInfo.setLogoUrl(coinBaseInfo.getLogo());
                }
                virtualInfo.setName(itShowInfo.getSymbol());
                virtualInfo.setNum(list.get(i).getNum().toPlainString());
                if(defaultSymbol()){
                    virtualInfo.setPrice(MoneyUtils.formatterCoin(itShowInfo.getPriceCny()));
                }else{
                    virtualInfo.setPrice(MoneyUtils.formatterCoin(itShowInfo.getPriceUsd()));
                }
                virtualInfo.setExchangePirce(MoneyUtils.formatterCoin(itShowInfo.getPriceUsd()));
                virtualInfo.setRange(RangeUtil.formatter(itShowInfo.getPercentChange24h()));
                virtualInfo.setVirtualId(list.get(i).getId());
                model.getPointList().add(pointInfo);
                model.getCoinList().add(virtualInfo);
            }
        }
        resoponse.setData(model);
        resoponse.success();
        return resoponse;
    }


    @ApiOperation(value = "put",notes = "新增虚拟资产")
    @RequestMapping(value = "put",method = RequestMethod.POST)
    public CommonResponse put(@RequestBody VirtualPutRequest request){
            CommonResponse response = new CommonResponse();
            UserInfo userInfo = getUser();
            if(userInfo == null){
                response.error(ResponseMsgEnum.USER_NOT_LOGIN);
                return response;
            }
            if(StringUtils.isEmpty(request.getUsName())&&StringUtils.isEmpty(request.getTargetId())){
                response.error("参数错误，targetId缺失");
                return  response;
            }

            UserVirtualAssetsInfo info = new UserVirtualAssetsInfo();
            info.setUserId(userInfo.getId());
            info.setTargetId(request.getTargetId());
            info.setAssetUnit(request.getAssetUnit());
            if(defaultSymbol()){
                info.setBuyTotal(new BigDecimal(request.getBuyTotal()));
            }else{
                String str = redisUtils.hget("COIN_GLOBAL","CNY");
                JSONObject obj = JSON.parseObject(str);
                info.setBuyTotal(new BigDecimal(request.getBuyTotal()).multiply(new BigDecimal(obj.getDouble("price_cny"))));
            }
            info.setNum(new BigDecimal(request.getNum()));
            info.setSavePlace(request.getSavePlace());
            info.setSaveMarketId(request.getSaveMarketId());
            info.setUsName(request.getTargetId());
            this.userVirtualAssetsInfoMapper.insert(info);
            response.success();
            return  response;

    }

    @ApiOperation(value = "detail/get",notes = "获取虚拟资产详情")
    @ApiImplicitParam(name = "virtualId",value = "虚拟资产主键")
    @RequestMapping(value = "detail/get",method = RequestMethod.GET)
    public VirturalGetResponse getDetail(@RequestParam Long virtualId){
            VirturalGetResponse response = new VirturalGetResponse();
            VirtualGetModel model = new VirtualGetModel();
            UserVirtualAssetsInfo info = this.userVirtualAssetsInfoMapper.selectPrimary(virtualId);
            if(info != null){
                MarketBaseInfo marketBaseInfo =  this.marketBaseInfoMapper.selectPrimary(info.getSaveMarketId());
                model.setAssetUnit(info.getAssetUnit());
                model.setBuyTotal(info.getBuyTotal().doubleValue());
                model.setMarketId(info.getSaveMarketId());
                model.setNum(info.getNum().doubleValue());
                model.setSavePlace(info.getSavePlace());
                model.setUsName(info.getUsName());
                model.setTargetId(info.getTargetId());
                if(marketBaseInfo != null)
                model.setMarketName(marketBaseInfo.getMarketName());
                CoinBaseInfo coinBaseInfo = this.coinBaseInfoUtils.get(info.getUsName());
                if(coinBaseInfo != null){
                    model.setSymbol(coinBaseInfo.getSymbol());
                }
            }
            response.setData(model);
            response.success();
            return response;
    }

    @ApiOperation(value = "update",notes = "修改虚拟资产详情")
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public CommonResponse update(@RequestBody VirturalUpdateRequest request){
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = getUser();
        if(userInfo == null){
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
        }else{
            UserVirtualAssetsInfo info = this.userVirtualAssetsInfoMapper.selectPrimary(request.getVirtualId());
            if(info == null){
                response.error("资产不存在");
            }else{
                if(request.getVirtualId() == null){
                    response.error("资产主键不存在");
                    return response;
                }
                info.setNum(request.getNum());
                info.setBuyTotal(request.getBuyTotal());
                info.setSavePlace(request.getSvaePlace());
                info.setAssetUnit(request.getAssetUnit());
                info.setSaveMarketId(request.getMarketId());
                info.setId(request.getVirtualId());
                this.userVirtualAssetsInfoMapper.updateById(info);
                response.success();
            }
        }
        return response;

    }

    @ApiOperation(value = "del",notes = "删除虚拟资产")
    @RequestMapping(value = "del",method = RequestMethod.POST)
    public CommonResponse del(@RequestBody VirtualDelRequest request){
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = getUser();
        if(userInfo == null){
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        String[] idx = request.getIds().split(",");
        for(String id : idx){
            this.userVirtualAssetsInfoMapper.delete(Long.valueOf(id));
        }
        response.success();
        return response;
    }
}
